// 公共方法

const db = require('../mysql/index')

// 根据Authorization获取用户id  传递进来的是token  const user_id = await commonFunction.getUserId(Authorization)
exports.getUserId = (Authorization) => {
    // 将登录用户的id找到
    const sqlId = 'SELECT id FROM user WHERE token = ?'
    return new Promise((resolve, reject) => {
        db.query(sqlId, Authorization, (err, result) => {
            if (err) reject(err)
            if (result.length !== 1) reject('暂无权限')
            resolve(result[0].id)
        })
    })
}

// 将省市区代码转为省市区名称  传递进来的是省市区代码的数组
exports.getCityName = (arr) => {
    const sql = 'SELECT province_name, city_name, area_name FROM province, city, area WHERE province_code = ? and city_code = ? and area_code = ?'
    return new Promise((resolve, reject) => {
        db.query(sql, arr, (err, result) => {
            if (err) reject(err)
            if (result.length !== 1) return false
            const areaNameArr = []
            result.forEach(item => {
                let areaName = item.province_name + item.city_name + item.area_name.trim()
                areaNameArr.push(areaName)
            });
            resolve(areaNameArr)
        })
    })
}


// 生成订单id
exports.order_id = () => {
    return new Date().getTime() + Math.random().toString(36).substring(2)
}
